/// 如何合理的显示一幅图像
#include <cctype>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <iostream>
#include <iomanip>

// opencv
#include "opencv2/calib3d.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"

using namespace cv;
using namespace std;

static void help()
{
    printf( "This is example how to show image.\n"
            "Usage: calibration\n"
            "     -imageFile=<imageFile>       # the image file\n"
            "\n");
}

Mat imageOrig;
Mat draw;
string winName = "image";

bool selectObject = false;
Rect selection;
Point origin;

static void onMouse( int event, int x, int y, int, void* userData)
{
    //Mat *pimage = (Mat*)userData;
    //Mat draw = pimage->clone();
    if (EVENT_MOUSEMOVE != event) {
        printf("onMouse, pos(%d, %d), event: %d\n", x,y, event); fflush(stdout);
    }
    if( selectObject )
    {
        selection.x = MIN(x, origin.x);
        selection.y = MIN(y, origin.y);
        selection.width = std::abs(x - origin.x);
        selection.height = std::abs(y - origin.y);
        //rectangle(draw, origin, Point(x,y), Scalar(0, 255, 0));
        //imshow(winName, draw);
    }
    switch( event )
    {
    case EVENT_LBUTTONDOWN:
        origin = Point(x,y);
        selection = Rect(x,y,0,0);
        selectObject = true;
        break;
    case EVENT_LBUTTONUP:
        selectObject = false;
        if( selection.width > 0 && selection.height > 0 )
        {
            Mat subImage = draw(selection);
            imshow(winName, subImage);
            draw = subImage.clone();
        }
        break;
    case EVENT_RBUTTONUP:
        draw = imageOrig.clone();
        imshow(winName, draw);
        break;
    }

}

int main(int argc, char *argv[])
{
    string imageFile;
    cv::CommandLineParser parser(argc, argv,
        "{help ||}{imageFile||}"
        );
    if (parser.has("imageFile")) {
        imageFile = parser.get<string>("imageFile");
    } else {
        imageFile = "E:/yd_datatest/circle_standard.bmp";
    }

    Mat view = imread(imageFile);
    circle(view, Point(300,300), 1, Scalar(0, 0, 255));
    imageOrig = view;
    draw = view.clone();
    namedWindow(winName, 0);
    setMouseCallback(winName, onMouse, &view);
    imshow(winName, view);
    waitKey();

    return 0;
}
